package com.blog.controller;

import com.blog.pojo.Message;
import com.blog.pojo.User;
import com.blog.service.FolloweeService;
import com.blog.service.MessageService;
import com.blog.service.UserService;
import com.blog.service.impl.FolloweeServiceImpl;
import com.blog.service.impl.MessageServiceImpl;
import com.blog.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;


@WebServlet("/messageServlet")
public class MessageServlet extends BaseServlet{
    private MessageService messageService = new MessageServiceImpl();
    private UserService userService = new UserServiceImpl();
    //发送信息
    public String addMessage(HttpServletRequest req, HttpServletResponse resp) {
        //1.登录验证
        HttpSession session=req.getSession();
        User user=(User)session.getAttribute("user");
        if(user==null){
            req.setAttribute("msg","请先登录");
            return "forward:/login.jsp";
        }
        //2.获取参数
        //获取发送人的id（senderId）
        int senderId=user.getId();
        String content=req.getParameter("content");
        String receiverId=req.getParameter("receiverId");//接受人Id
        int receiverIdInt=Integer.parseInt(receiverId);

        Message message=new Message();
        message.setSenderId(senderId);
        message.setReceiverId(receiverIdInt);
        message.setContent(content);

        //A B两个人，情况一：A关注B; 情况二：B关注A 情况三：A和B互关 情况四：A和B无关注
        //假设A给B发信息， 情况一 二 四都只可以发送一条，情况三可以发送多条
        //先验证是否A和B关注状态
        //status = 0：A 和 B 无关注关系，可以发送多条消息。
        //status = 1：A 关注 B 或 B 关注 A，但不是互关，只能发送一条消息。
        //status = 2：A 和 B 互相关注，可以发送多条消息。
        long status=messageService.followeeSenderReceiver(senderId,receiverIdInt);
        if( status>1){
            messageService.addMessage(message);
        } else if (status==1) {
          //先检查是否已经发送过消息
            boolean isExist = messageService.countSenderRecevier(senderId,receiverIdInt);
            if(!isExist){
                messageService.addMessage(message);
                req.setAttribute("message", "你已发送给对方一条信息，等对方回关你后可继续发送信息！！！");
            }else{
                req.setAttribute("message", "你已经发送过消息，等对方回关你后可继续发送信息！！！");
            }
        }else{
            req.setAttribute("message", "您还未关注对方，请先关注对方！！！");
        }
        return "forward:/userProfile.jsp";
    }
    //删除信息，情况一：自己可以删除自己发送的 情况二：自己可以删除自己接收的
    public String deleteMessage(HttpServletRequest req, HttpServletResponse resp) {
        //获取参数
        String id = req.getParameter("id");
        //1.登录验证
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            req.setAttribute("msg", "请先登录");
            return "forward:/login.jsp";
        }
        int idInt = Integer.parseInt(id);
        //根据id查询信息
        Message message = messageService.findById(idInt);

        if (message == null) {
            req.setAttribute("msg", "没有此信息");
        }
            if (message.getReceiverId() == user.getId() || message.getSenderId() == user.getId()) {

                messageService.deleteMessage(idInt);
                req.setAttribute("msg", "删除成功");
                return "forward:/messageServlet?method=findMessageBySenderId";

            } else {
                req.setAttribute("msg", "删除失败");
                return "forward:/messageServlet?method=findMessageBySenderId";
            }
        }
  //查询已发送的消息--senderId
  public String findMessageBySenderId(HttpServletRequest req, HttpServletResponse resp) {
        //登录验证
      HttpSession session = req.getSession();
      User user = (User) session.getAttribute("user");
      if (user == null) {
          req.setAttribute("msg", "请先登录");
          return "forward:/login.jsp";
      }
      //参数获取 senderId
     int senderId= user.getId();
      List<Message> messagesList=messageService.findMessageBySenderId(senderId);
      //接受人的名字
      for(Message message:messagesList){
          User user1 = userService.findById(message.getReceiverId());
          message.setReceiverName(user1.getUsername());
      }
      req.setAttribute("sentList",messagesList);
      return "forward:/sentList.jsp";
  }
  //查看收件箱
  public String findMessageByReceiveId(HttpServletRequest req, HttpServletResponse resp) {
        //登录验证
      HttpSession session=req.getSession();
      User user = (User) session.getAttribute("user");
      if(user==null){
          req.setAttribute("msg","请先登录");
          return "forward:/login.jsp";
      }
          //获取用户id
         int receiveId=user.getId();
          //调用业务层
          List<Message> messagesList=messageService.findMessageByReceiveId(receiveId);
      //发送者名字
         for (Message message : messagesList) {
             User u = userService.findById(message.getSenderId());
             message.setSenderName(u.getUsername());
         }
          req.setAttribute("receiveList",messagesList);
          return "forward:/receiveList.jsp";
  }
//查看A和B全部聊天记录
    public String findMessageBySenderAndReceiver(HttpServletRequest req, HttpServletResponse resp){
        //假设AB互相发消息，登录人是A，A点击和B的聊天框，查看两个人全部聊天信息
        //获取发送人id（B）
        String senderId=req.getParameter("senderId");
        //登录验证
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){
            req.setAttribute("msg","请先登录");
            return "forward:/login.jsp";
        }
        //获取接收人id（A）
        int receiveId=user.getId();
        int senderIdInt=Integer.parseInt(senderId);

        List<Message> messages = messageService.findMessageBySenderAndReceiver(senderIdInt, receiveId);
        if(messages==null){
            req.setAttribute("msg","暂无聊天消息");
        }
        req.setAttribute("messages",messages);
        return "forward:chat.jsp";
    }
    //信息已读
    public String markAsRead(HttpServletRequest req, HttpServletResponse resp) {
       //获取信息id
        String id = req.getParameter("id");
        //登录验证
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            req.setAttribute("msg", "请先登录");
            return "forward:/login.jsp";
        }
        int idInt = Integer.parseInt(id);
        boolean isread = messageService.updateMessage(idInt, (byte) 1);
        if (isread) {
            return "forward:/chat.jsp";
        } else {
            req.setAttribute("msg", "操作失败");
            return "forward:/chat.jsp";
        }
    }

}
